/* 业务依赖 */
const fs = require("fs");
const path = require("path")
const { uploadPath } = require("../config");

function receiveUploadedFile(req) {
    return new Promise((resolve, reject) => {
        fs.readFile(req.files[0].path, (err, data) => {
            if (err) {
                resolve({
                    msg: "文件上传失败",
                    err,
                });
            } else {
                console.log("data=", data);

                if (data) {
                    /* 如果读取成功，将其写入upload目录下 */
                    const filePath = path.join(uploadPath, req.files[0].filename)
                    fs.writeFile(
                        filePath,
                        data,
                        (err) => {
                            err
                                ? resolve({
                                      msg: "文件上传失败",
                                      err,
                                  })
                                : resolve({
                                      msg: "文件上传成功",
                                      filename:req.files[0].filename
                                  });
                        }
                    );
                } else {
                    resolve({
                        msg: "文件上传失败",
                        err,
                    });
                }
            }
        });
    });
}

module.exports = {
    receiveUploadedFile,
};
